/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package studio.raptor.ddal.core.connection.jdbc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import studio.raptor.ddal.core.connection.ConnectionFactory;

/**
 * Jdbc connection creator
 *
 * @author Sam
 * @since 3.0.0
 */
public class JdbcConnectionFactory implements ConnectionFactory<JdbcBackendConnection> {

  private static Logger LOGGER = LoggerFactory.getLogger(JdbcConnectionFactory.class);

  private Driver driver;
  private String driverClassName;
  private String connectUri;
  private Properties connectionProperties;
  private int connectionFetchSize;


  /**
   * The class loader instance to use to load the JDBC driver. If not
   * specified, {@link Class#forName(String)} is used to load the JDBC driver.
   * If specified, {@link Class#forName(String, boolean, ClassLoader)} is
   * used.
   */
  private ClassLoader driverClassLoader = null;

  public JdbcConnectionFactory(String driverClassName, String connectUri, String username, String password) throws SQLException {
    this(driverClassName, connectUri, username, password, new Properties());
  }

  private JdbcConnectionFactory(String driverClassName, String connectUri, String username, String password, Properties connectionProperties) throws SQLException {
    this.driverClassName = driverClassName;
    this.connectUri = connectUri;
    this.connectionProperties = connectionProperties;
    this.connectionProperties.setProperty("user", username);
    this.connectionProperties.setProperty("password", password);
    // todo 做成配置的
    connectionFetchSize = 25;
    loadDriver();
  }

  /**
   * Returns the class loader specified for loading the JDBC driver. Returns
   * <code>null</code> if no class loader has been explicitly specified.
   * <p>
   * Note: This getter only returns the last value set by a call to
   * {@link #setDriverClassLoader(ClassLoader)}. It does not return the class
   * loader of any driver that may have been set via
   * {@link #setDriver(Driver)}.
   */
  public synchronized ClassLoader getDriverClassLoader() {
    return this.driverClassLoader;
  }

  /**
   * <p>Sets the class loader to be used to load the JDBC driver.</p>
   * <p>
   * Note: this method currently has no effect once the pool has been
   * initialized.  The pool is initialized the first time one of the
   * following methods is invoked: <code>getConnection, setLogwriter,
   * setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
   *
   * @param driverClassLoader the class loader with which to load the JDBC driver
   */
  public synchronized void setDriverClassLoader(
          ClassLoader driverClassLoader) {
    this.driverClassLoader = driverClassLoader;
  }

  private void setDriver(Driver driver) {
    this.driver = driver;
  }

  /**
   * Load JDBC driver if driver is not specified or driver classname is specified.
   *
   * @throws SQLException SQLException
   */
  private void loadDriver() throws SQLException {
    // Load the JDBC driver class
    Driver driverToUse = this.driver;
    if (driverToUse == null) {
      Class<?> driverFromCCL = null;
      if (driverClassName != null) {
        try {
          try {
            if (driverClassLoader == null) {
              driverFromCCL = Class.forName(driverClassName);
            } else {
              driverFromCCL = Class.forName(driverClassName, true, driverClassLoader);
            }
          } catch (ClassNotFoundException cnfe) {
            driverFromCCL = Thread.currentThread().getContextClassLoader().loadClass(driverClassName);
          }
        } catch (Exception t) {
          String message = "Cannot load JDBC driver class '" + driverClassName + "'";
          throw new SQLException(message, t);
        }
      }
      try {
        if (driverFromCCL == null) {
          driverToUse = DriverManager.getDriver(connectUri);
        } else {
          // Usage of DriverManager is not possible, as it does not
          // respect the ContextClassLoader
          // N.B. This cast may cause ClassCastException which is handled below
          driverToUse = (Driver) driverFromCCL.newInstance();
          if (!driverToUse.acceptsURL(connectUri)) {
            throw new SQLException("No suitable driver", "08001");
          }
        }
      } catch (Exception t) {
        String message = "Cannot create JDBC driver of class '" +
                (driverClassName != null ? driverClassName : "") +
                "' for connect URL '" + connectUri + "'";
        throw new SQLException(message, t);
      }

      // set loaded driver to this factory
      setDriver(driverToUse);
    }
  }

  @Override
  public JdbcBackendConnection createConnection() {
    JdbcBackendConnection jdbcBackendConnection = null;
    try {
      DriverManager.registerDriver(driver);
      jdbcBackendConnection = new JdbcBackendConnection(DriverManager.getConnection(connectUri, this.connectionProperties));
      jdbcBackendConnection.setFetchSize(this.connectionFetchSize);
    } catch (SQLException sqlException) {
      LOGGER.error("", sqlException);
    }
    return jdbcBackendConnection;
  }
}
